package com.qc.controller.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qc.common.ImageUtils;
import com.qc.common.QiNiuUtil;
import com.qc.common.StringUtil;
import com.qc.entity.BannerEntity;
import com.qc.entity.HeightEntity;
import com.qc.pageUtil.page.page.Page;
import com.qc.pageUtil.page.page.PageModel;
import com.qc.pageUtil.page.page.PageModelList;
import com.qc.pageUtil.page.vo.NewsAndNav;
import com.qc.service.BannerService;


@SuppressWarnings({ "rawtypes", "unchecked" })
@Controller
@RequestMapping("/web")
public class WebBannerController {

    @Resource(name="bannerService")
    private BannerService bannerService;
    
    /**
     * 跳转身高到首页
     * @return
     */
    @RequestMapping(value = "/toBannerIndex", produces = "text/html;charset=UTF-8")
    public ModelAndView toBannerIndex() {
        ModelAndView mav = new ModelAndView("/banner/banner_zhuye");
        return mav;
    }
    
    @RequestMapping(value = "/toBannerInformIndex", produces = "text/html;charset=UTF-8")
    public ModelAndView toBannerInformIndex(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/banner/banner_xiugai");
        
        String id = request.getParameter("id");
        
        BannerEntity bannerEntity = bannerService.getBannerEntity(id);
        mav.addObject("bannerEntity",bannerEntity);
        
        return mav;
    }
    
    @RequestMapping(value = "/toBannerAdd", produces = "text/html;charset=UTF-8")
    public ModelAndView toBannerAdd() {
        ModelAndView mav = new ModelAndView("/banner/banner_add");
        
        return mav;
    }
    
    /**
     * 身高数据展示
     * @param request
     * @return
     */
    @RequestMapping(value = "/toListAllBanner", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String toListAllBanner(HttpServletRequest request) {
        
        String name = request.getParameter("name");
        //当前页面
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        //每页显示多少条
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        
        //根据条件总数
        int recordCount = bannerService.getListBannerCount(name);
        
        //根据条件查询当前页数据
        List<HeightEntity> list = bannerService.getAllBanner(name, pageNo, pageSize);
        
        //分页查询公共类
        Page<HeightEntity> page = new Page<HeightEntity>(pageNo, recordCount,pageSize);
        page.setList(list);//设置结果集  
        PageModelList<HeightEntity> pageModel = new PageModelList<HeightEntity>(page, "#", PageModel.NUM_MODEL,"doPage","1");//设置页码显示类型  
        //4 组装带翻页导航功能的对象
        NewsAndNav  objs = new NewsAndNav(list, pageModel.getPageModel());
        
        return JSONObject.fromObject(objs).toString();
        
    }
    
    
    /**
     * 身高添加
     * @throws Exception 
     */
    @RequestMapping(value = "/toSaveBanner")
    public ModelAndView toSaveBanner(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws Exception {
        
        ModelAndView mav = new ModelAndView("redirect:/web/toBannerIndex.do");
        
        String url = request.getSession().getServletContext().getRealPath("/")+("/fileImage");
          
        String name = request.getParameter("name");
        int level = Integer.parseInt(request.getParameter("level"));
        int open = Integer.parseInt(request.getParameter("open"));
        String parameter = request.getParameter("parameter");
        int position = Integer.parseInt(request.getParameter("position"));
        int type = Integer.parseInt(request.getParameter("type"));
        
        //获取图片名称
        String fileName = file.getOriginalFilename();
        
        //目录不存在 新建一个
        File f1=new File(url); 
        if(!f1.isDirectory()) {
            f1.mkdir();
        }
        //创建时间参数
        SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");// 文件重命名
        String namefile = bartDateFormat.format(new Date());
        
        InputStream stream = file.getInputStream();// 把文件读入
        
        //图片名字
        fileName = namefile + fileName.substring(fileName.indexOf("."));// 保存文件路径和文件名
        OutputStream bos = new FileOutputStream(url + "/" + fileName);// 建立一个上传文件的路径
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
            // 将文件写入服务器
            bos.write(buffer, 0, bytesRead);
        }
        bos.close();
        stream.close();
        
        String path = url + "/" + fileName;
        
        ImageUtils.scale(path, path, 1, true);
        
        try {
            QiNiuUtil.upload(path, "web_dev_14_qiniu_"+fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        BannerEntity bannerEntity = new BannerEntity();
        
        bannerEntity.setName(name);
        bannerEntity.setImgUrl("web_dev_14_qiniu_"+fileName);
        bannerEntity.setLevel(level);
        bannerEntity.setOpen(open);
        bannerEntity.setParameter(parameter);
        bannerEntity.setPosition(position);
        bannerEntity.setType(type);
        bannerEntity.setCount(0);
        
        int flag = bannerService.saveBanner(bannerEntity);
        if (flag == 1) {
            return mav;
        }else {
            mav = new ModelAndView("redirect:/web/toBannerAdd.do");
        }
        return mav;
    }
    
    /**
     * banner删除
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toDeleteBannerId")
    @ResponseBody
    public int toDeleteBannerId(HttpServletRequest request,HttpServletResponse response) {
        long id = Long.parseLong(request.getParameter("id"));
        int flag = bannerService.deleteBannerId(id);
        return flag;
    }
    
    /**
     * banner修改
     * @throws IOException 
     */
    
    @RequestMapping(value = "/toUpdateBannerId")
    public ModelAndView toUpdateBannerId(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        ModelAndView mav = new ModelAndView("redirect:/web/toBannerIndex.do");
        
        BannerEntity bannerEntity = new BannerEntity();
        
        String url = request.getSession().getServletContext().getRealPath("/")+("/fileImage");
        
        long id = Long.parseLong(request.getParameter("id"));
        String name = request.getParameter("name");
        String imgUrl = request.getParameter("imgUrl");
        int level = Integer.parseInt(request.getParameter("level"));
        int open = Integer.parseInt(request.getParameter("open"));
        String parameter = request.getParameter("parameter");
        int position = Integer.parseInt(request.getParameter("position"));
        int type = Integer.parseInt(request.getParameter("type"));
        
        //获取图片名称
        String fileName = file.getOriginalFilename();
        if (StringUtil.isNotEmpty(fileName)) {
            //目录不存在 新建一个
            File f1=new File(url); 
            if(!f1.isDirectory()) {
                f1.mkdir();
            }
            //创建时间参数
            SimpleDateFormat bartDateFormat = new SimpleDateFormat("yyyyMMddhhmmssSSS");// 文件重命名
            String namefile = bartDateFormat.format(new Date());
            
            InputStream stream = file.getInputStream();// 把文件读入
            
            //图片名字
            fileName = namefile + fileName.substring(fileName.indexOf("."));// 保存文件路径和文件名
            OutputStream bos = new FileOutputStream(url + "/" + fileName);// 建立一个上传文件的路径
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                // 将文件写入服务器
                bos.write(buffer, 0, bytesRead);
            }
            bos.close();
            stream.close();
            
            String path = url + "/" + fileName;
            
            ImageUtils.scale(path, path, 2, true);
            
            try {
                QiNiuUtil.upload(path, "web_dev_14_qiniu_"+fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            bannerEntity.setImgUrl("web_dev_14_qiniu_"+fileName);
        }else {
            bannerEntity.setImgUrl(imgUrl);
        }
        
        bannerEntity.setName(name);
        bannerEntity.setLevel(level);
        bannerEntity.setOpen(open);
        bannerEntity.setParameter(parameter);
        bannerEntity.setPosition(position);
        bannerEntity.setType(type);
        bannerEntity.setId(id);
        
        int flag = bannerService.updateBannerId(bannerEntity);
        
        if (flag == 1) {
            
            return mav;
        }else {
            
            mav = new ModelAndView("redirect:/web/toBannerInformIndex.do?id="+bannerEntity.getId());
        }
        return mav;
    }
}
